<!--
 * @author  dumeng
-->
<template>
  <div class="works-create">
    <div class="works-create-title">上传作品</div>
    <section v-loading="loading" class="works-create-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="作品名称" prop="worksName">
          <el-input v-model="form.worksName" placeholder="请输入作品名称" />
        </el-form-item>
        <el-form-item label="作者" prop="authorId">
          <div v-if="!form.authorId" class="selectbtn" @click="showuser = true">选择人员</div>
          <template v-else>
            <div class="select-data">
              {{ form.authorRealName }}
              <i v-if="state === 'create'" class="el-icon-close" @click="clearPerson" />
            </div>
          </template>
        </el-form-item>
        <template v-if="form.authorId">
          <el-form-item label="手机号码" prop="authorPhoneNumber">
            <el-input v-model="form.authorPhoneNumber" disabled />
          </el-form-item>
          <el-form-item label="证件号码" prop="authorIdNumber">
            <el-input v-model="form.authorIdNumber" disabled />
          </el-form-item>
          <el-form-item label="所在部门" prop="deptName">
            <el-input v-model="form.deptName" disabled />
          </el-form-item>
        </template>

        <el-form-item label="作品封面" prop="worksCover" required>
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.worksCover"
            :preview-id="uploadFile.viewId"
            :forever="true"
            :width="270"
            :view="uploadFile.view"
            :height="180"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>

        <el-form-item
          v-if="isAutonomyUpload"
          label="作品说明"
          prop="worksRemark"
        >
          <el-input
            v-if="isAutonomyUpload === '1'"
            v-model="form.worksRemark"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6}"
            placeholder="请输入作品说明"
          />
          <tinymce
            v-else-if="isAutonomyUpload === '0' && showtinymce"
            v-model="form.worksRemark"
            :height="300"
          />
        </el-form-item>
        <el-form-item label="图片作品">
          <div class="selectbtn" @click="handleFileUpload('image')">添加图片</div>
          <el-card v-if="imagesList.length" class="news-image">
            <el-row :gutter="10">
              <draggable
                v-model="imagesList"
                :animation="340"
                handle=".image-index-move"
                filter=".no-drag-item"
                draggable=".drag-item"
              >
                <el-col
                  v-for="(item, index) in imagesList"
                  :key="item"
                  :span="8"
                  class="images-item"
                  :class="{'no-drag-item': !item , 'drag-item': item }"
                >
                  <div class="custom-uploader">
                    <img class="upload-img" :src="uploadFile.view + item">
                    <el-button
                      style="padding: 3px 0; font-size: 20px;"
                      type="text"
                      icon="el-icon-close"
                      @click="imagesDel(index)"
                    />
                    <el-tooltip class="item" effect="dark" content="拖动调整顺序" placement="top">
                      <el-button
                        class="image-index-move"
                        style="padding: 3px 0; font-size: 20px;"
                        type="text"
                        icon="el-icon-rank"
                      />
                    </el-tooltip>
                  </div>
                </el-col>
              </draggable>
            </el-row>
          </el-card>
        </el-form-item>
        <el-form-item label="视频作品">
          <div class="selectbtn" @click="handleFileUpload('video')">添加视频</div>
          <el-card v-if="videosList.length">
            <el-row class="attachment-item" :gutter="10">
              <draggable v-model="videosList" :animation="340" handle=".video-index-move">
                <el-col
                  v-for="(item, index) in videosList"
                  :key="item"
                  :span="8"
                  class="video-item"
                >
                  <template v-if="item">
                    <img
                      v-if="item"
                      class="upload-img"
                      src="../images/video-poster.png"
                      @click="handlePreview(item, index)"
                    >
                    <el-button
                      style="padding: 3px 0; font-size: 20px;"
                      type="text"
                      icon="el-icon-close"
                      @click="videosDel(item, index)"
                    />
                    <el-tooltip class="item" effect="dark" content="拖动调整顺序" placement="top">
                      <el-button
                        class="video-index-move"
                        style="padding: 3px 0; font-size: 20px;"
                        type="text"
                        icon="el-icon-rank"
                      />
                    </el-tooltip>
                  </template>
                </el-col>
              </draggable>
            </el-row>
          </el-card>
        </el-form-item>
      </el-form>
    </section>
    <section class="works-create-footer">
      <el-button style="padding: 10px 30px" @click="() => {$router.back();}">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <video-upload
      v-if="uploadFile.showUpload===1"
      ref="videoUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </video-upload>
    <image-no-cropper-upload
      v-if="uploadFile.showUpload===2"
      ref="imageUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </image-no-cropper-upload>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="preview.state"
      title="预览"
      center
      width="600px"
    >
      <preview :file-id="preview.fileId" />
    </el-dialog>
    <v-user v-if="showuser" :id="form.authorId" @comit="handleUserComit" @cancel="showuser = false" />
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import VUser from '../components/user'
import VideoUpload from '@/components/VideoUpload'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload' // base on element-ui
import Preview from '../components/VideoPreview'
import draggable from 'vuedraggable'
import { mapGetters } from 'vuex'
import {
  getDictByCode,
  insert,
  update,
  get,
  getActivityDetail
} from '../api/works'
import Tinymce from '@/components/Tinymce'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import CryptoJS from '@/utils/aesJiaJM'

export default {
  name: 'WorksCreate',
  components: { ImageNoCropperUpload, VideoUpload, ImageUpload, Tinymce, VUser, Preview, draggable },
  directives: { elDragDialog },
  filters: {
    filterTip(ft) {
      if (ft === 'image') {
        return '只能上传：图片文件'
      } else if (ft === 'video') {
        return '只能上传：视频文件'
      }
    }
  },
  data() {
    return {
      loading: false,
      showtinymce: false,
      form: {
        id: '',
        worksName: '',
        authorId: '',
        authorRealName: '',
        authorPhoneNumber: '',
        authorIdNumber: '',
        deptName: '',
        worksCover: '',
        worksRemark: ''
      },
      rules: {
        worksName: [
          { required: true, message: '请输入作品名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        authorId: [
          { required: true, message: '请选择作者', trigger: 'change' }
        ],
        worksRemark: [
          { required: true, message: '请输入作品说明', trigger: 'change' }

        ],
        worksCover: [
          { required: true, message: '请上传引导图', trigger: 'change' }
        ]
      },
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: ''
      },
      showuser: false,
      videosList: [],
      imagesList: [],
      imageaddState: false,
      imageadd: {
        attachmentId: '',
        explain: '',
        attachmentName: ''
      },
      preview: {
        state: false,
        fileId: ''
      },
      isAutonomyUpload: ''// 允许上传的，1 是多行文本，0 不允许的是富文本
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.getActivityDetail(this.$route.query.pi)
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.pi) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
        return
      }
      this.getData(this.$route.query.i)
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    clearPerson() {
      this.form.authorId = ''
      this.form.authorRealName = ''
      this.form.authorPhoneNumber = ''
      this.form.authorIdNumber = ''
      this.form.deptName = ''
    },
    handleUserComit(data) {
      if (data && data.length > 0) {
        this.form.authorId = data[0].id
        this.form.authorRealName = data[0].userRealname
        this.form.authorPhoneNumber = data[0].jieMphoneNumber
        this.form.authorIdNumber = data[0].jieMuserIdnumber
        this.form.deptName = data[0].deptName
        this.showuser = false
      }
    },
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.imagesList.length === 0 && this.videosList.length === 0) {
              this.$message({
                message: '图片作品/视频作品最少上传一种！',
                type: 'warning'
              })
              return
            }
            const params = Object.assign({}, this.form)
            params['imgIds'] = this.imagesList.join(',')
            params['videoIds'] = this.videosList.join(',')
            params['solicitationId'] = this.$route.query.pi
            delete params.authorRealName
            delete params.authorPhoneNumber
            delete params.authorIdNumber
            delete params.deptName
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.imagesList.length === 0 && this.videosList.length === 0) {
              this.$message({
                message: '图片作品/视频作品最少上传一种！',
                type: 'warning'
              })
              return
            }
            const params = Object.assign({}, this.form)
            params['imgIds'] = this.imagesList.join(',')
            params['videoIds'] = this.videosList.join(',')
            params['solicitationId'] = this.$route.query.pi
            delete params.authorRealName
            delete params.authorPhoneNumber
            delete params.authorIdNumber
            delete params.deptName
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                // eslint-disable-next-line no-undef
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                // eslint-disable-next-line no-undef
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          const jmList = ['authorIdNumber', 'authorPhoneNumber']
          for (const key in this.form) {
            if (jmList.indexOf(key) > -1) {
              this.form[key] = CryptoJS.$aesJieM(data[key])
            } else {
              this.form[key] = data[key]
            }
          }
          this.uploadFile.viewId = data.worksCover
          this.imagesList = data.imgIds ? data.imgIds.split(',') : []
          this.videosList = data.videoIds ? data.videoIds.split(',') : []
          this.showtinymce = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 获取是否允许自主上传
     */
    getActivityDetail(activityId) {
      return new Promise((resolve, reject) => {
        getActivityDetail({ id: activityId }).then(res => {
          if (res.data.data) {
            this.isAutonomyUpload = res.data.data.isAutonomyUpload || ''
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    uploadSuccess(id, files) {
      if (id) {
        const fileType = this.uploadFile.fileType
        if (fileType === 'image') {
          this.imagesList.push(id)
        } else if (fileType === 'video') {
          this.videosList.push(id)
        }
      }
      this.uploadFile.showUpload = -1
    },
    /**
     * 视频预览
     */
    handlePreview(id) {
      this.preview.fileId = id
      this.preview.state = true
    },
    handleFileUpload(fileType, i) {
      this.uploadFile.fileType = fileType
      if (fileType === 'video') {
        this.uploadFile.accept = 'video/mp4'
        this.uploadFile.showUpload = 1
      } else if (fileType === 'image') {
        this.uploadFile.accept = 'image/*'
        this.uploadFile.showUpload = 2
      }
    },
    submitUploadImage() {
      const obj = Object.assign({}, this.imageadd)
      this.imagesList.push(obj)
      this.imageaddState = false
    },
    /**
     * 新闻图片-删除
     */
    imagesDel(index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imagesList.splice(index, 1)
      }).catch()
    },
    /**
     * 新闻视频-删除
     */
    videosDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.videosList.splice(index, 1)
      }).catch()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.works-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .works-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .works-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .works-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .images-item {
      position: relative;
      margin-bottom: 10px;

      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }

      .el-input {
        display: block;
      }

      .custom-uploader {
        width: 100%;
        display: block;

        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }

      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;

        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }

        &.image-index-move {
          right: 40px;
        }
      }
    }

    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }

    .upload-img {
      width: 100%;
      height: 160px;
    }

    .attachment-item {
      margin-bottom: 10px;

      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }

      .video-item {
        position: relative;
        cursor: pointer;

        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;

          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }

          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .works-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
<style lang="scss">

.works-create {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }

  .el-tag--medium {
    line-height: 32px;
    height: 32px;

    & + .el-tag--medium {
      margin-left: 10px;
    }
  }
}
</style>
